<?php
session_start();

//连接数据库
try {
function success(){
    $result=[
        'error' => 0,
        'message' => '成功'
    ];
    return json_encode($result);
}
function error($mag){
    $data = [
        'error' => 1,
        'message' => $mag
    ];
    return json_encode($data);
}
    //文件上传
    if(!isset($_FILES['userImg'])){
        die('无文件上传');
    };
    if($_FILES['userImg']['error'] != 0){
        die('无文件上传');
    };
    $allow=[
        'image/.jpeg',
        'image/.png',
        'image/.gif'
    ];
    if(in_array($_FILES['userImg']['type'],$allow)){
        die('禁止上传该类型！');
    };
    $file_name=$_FILES['userImg']['name'];
    $file_name=explode('.',$file_name)[1];
    $file_name=$_POST['username'].'.'.$file_name;
    $file_name='../upload/'.$file_name;
    move_uploaded_file($_FILES['userImg']['tmp_name'],$file_name);
    //连接数据库
    $db = new PDO('mysql:dbname=liaotian;host=106.14.7.147','root','123456');
    $search = $db->prepare('select * from user where username=:username');
    $search->execute([
        ':username'=> $_POST['username']
    ]);
    $reSearch=$search->fetch();
    if($_POST['username'] ==$reSearch['username']){
        die(error('用户名已存在'));
    };

    $add= $db->prepare('insert into user (username,password,repassword,nicheng,csri,sex,userImg) 
                      values(:username,:password,:repassword,:nicheng,:csri,:sex,:userImg)');
    $data[':username']=$_POST['username'];
    $data[':password']=$_POST['password'];
    $data[':repassword']=$_POST['repassword'];
    $data[':nicheng']=$_POST['nicheng'];
    $data[':csri']=$_POST['csri'];
    $data[':sex']=$_POST['sex'];
    $data[':userImg']=$file_name;

    if($add->execute($data) === false){
        print_r($add->errorInfo());
    }
    $re=$add->fetch();
    if(empty($_POST['username'])){
        die(error('用户名不能为空'));
    };
    if(empty($_POST['password'])){
        die(error('密码不能为空'));
    }
    if(empty($_POST['repassword'])){
        die(error('重复密码不能为空'));
    }
    if(empty($_POST['nicheng'])){
        die(error('昵称不能为空'));
    }
    if(empty($_POST['csri'])){
        die(error('出生日期不能为空'));
    }
    if(empty($_POST['sex'])){
        die(error('性别不能为空'));
    }
    if(empty($_FILES['userImg'])){
        die(error('头像不能为空'));
    }

    if($_POST['repassword'] != $_POST['password']){
        die(error('密码不一致'));
    }
    echo success();
} catch (PDOException $e) {
    echo 'Connection failed';
}
